package com.hjx.windowtool.cmd;

import java.awt.EventQueue;
import java.awt.FileDialog;

import javax.swing.JFrame;
import javax.swing.JSplitPane;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JMenu;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.border.LineBorder;
import javax.swing.plaf.FileChooserUI;

import com.hjx.windowtool.db.Tool;
import com.hjx.windowtool.util.StrUtil;

import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
@Tool("CMD运行工具")
public class CmdToolApp {

	private JFrame frame;
	private JTextField txt_name;
	private JTextArea txt_cmd;
	private JTextField txt_workdir;
	private JTextArea txtMsg;
	private JButton btn_run;
	private JMenu menu_1;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
					CmdToolApp window = new CmdToolApp();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public CmdToolApp() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 450, 367);
		frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		
		JSplitPane splitPane = new JSplitPane();
		splitPane.setResizeWeight(0.5);
		splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
		frame.getContentPane().add(splitPane, BorderLayout.CENTER);
		splitPane.addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				System.out.println(splitPane.getBounds());
				splitPane.setResizeWeight(150/splitPane.getBounds().height);
			}
		});
		
		JPanel panel = new JPanel();
		splitPane.setLeftComponent(panel);
		panel.setLayout(null);
		
		JLabel label = new JLabel("命令名称");
		label.setBounds(10, 10, 54, 15);
		panel.add(label);
		
		txt_name = new JTextField();
		txt_name.setBounds(68, 7, 145, 21);
		panel.add(txt_name);
		txt_name.setColumns(10);
		
		JLabel label_1 = new JLabel("运行命令");
		label_1.setBounds(10, 59, 54, 15);
		panel.add(label_1);
		
		btn_run = new JButton("运行");
		btn_run.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				btn_run.setEnabled(false);
				runCmd(txt_cmd.getText(),txt_workdir.getText());
			}
		});
		btn_run.setBounds(68, 104, 93, 23);
		panel.add(btn_run);
		
		txt_cmd = new JTextArea();
		txt_cmd.setLineWrap(true);
		txt_cmd.setBorder(new LineBorder(new Color(0, 0, 0)));
		txt_cmd.setBounds(68, 56, 354, 38);
		panel.add(txt_cmd);
		
		JLabel label_2 = new JLabel("运行目录");
		label_2.setBounds(10, 35, 54, 15);
		panel.add(label_2);
		
		txt_workdir = new JTextField();
		txt_workdir.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount()==2) {
					JFileChooser f=new JFileChooser(txt_workdir.getText());
					f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
					f.showOpenDialog(frame);
					File file = f.getSelectedFile();
					if (file==null) {
						return;
					}
					txt_workdir.setText(file.getAbsolutePath());
				}
			}
		});
		txt_workdir.setBounds(68, 32, 354, 21);
		panel.add(txt_workdir);
		txt_workdir.setColumns(10);
		
		JPanel panel_1 = new JPanel();
		splitPane.setRightComponent(panel_1);
		panel_1.setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		panel_1.add(scrollPane, BorderLayout.CENTER);
		
		txtMsg = new JTextArea();
		scrollPane.setViewportView(txtMsg);
		
		JMenuBar menuBar = new JMenuBar();
		frame.setJMenuBar(menuBar);
		
		JMenu menu = new JMenu("菜单");
		menuBar.add(menu);
		
		menu_1 = new JMenu("命令列表");
		menu_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				save();
				load();
			}
		});
		menu.add(menu_1);
		
		JMenuItem menuItem = new JMenuItem("命令1");
		menu_1.add(menuItem);
		menuItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				
				
			}
		});
		
		JMenuItem menuItem_1 = new JMenuItem("退出");
		menuItem_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (!btn_run.isEnabled()) {
					int showConfirmDialog = JOptionPane.showConfirmDialog(frame, "脚本正在运行,确认退出？");
					if (showConfirmDialog!=0) {
						return;
					}
				}
				frame.dispose();
//				System.exit(0);
			}
		});
		
		JMenuItem menuItem_2 = new JMenuItem("保存脚本");
		menuItem_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				save();
			}
		});
		menu.add(menuItem_2);
		menu.add(menuItem_1);
		load();
	}
	List<JMenuItem> listCmds=new ArrayList<>();
	protected void load() {
		File file =new File(System.getProperty("user.dir")+"/cmdsave");
		if (!file.exists()||!file.isDirectory()) {
			return;
		}
		menu_1.removeAll();
		for (File f : file.listFiles()) {
			JMenuItem menuItem = new JMenuItem(f.getName().substring(0, f.getName().lastIndexOf(".")));
			menu_1.add(menuItem);
			menuItem.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					try {
						List<String> list = Files.readAllLines(f.toPath());
						txt_name.setText(list.get(0));
						txt_workdir.setText(list.get(1));
						txt_cmd.setText(list.get(2));
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			});
			listCmds.add(menuItem);
		}
		menu_1.revalidate();
		menu_1.repaint();
	}

	public void save(){
		String name = txt_name.getText();
		String workdir = txt_workdir.getText();
		String cmd = txt_cmd.getText();
		if (StrUtil.isEmpty(name)||StrUtil.isEmpty(workdir)||StrUtil.isEmpty(cmd)) {
			return;
		}
		apend("保存数据：name="+name+"=workdir="+workdir+"=cmd="+cmd);
		try {
			File file =new File(System.getProperty("user.dir")+"/cmdsave/"+name+".javaobj");
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			Files.write(file.toPath(), Arrays.asList(name,workdir,cmd));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void runCmd(String text,String workdir) {
		apend(workdir+">"+text);
		new  Thread(new Runnable() {
			public void run() {
				Process p=null;
				try {
					p = Runtime.getRuntime().exec(new String[]{"cmd","/c",text},null,new File(workdir));
					InputStream is = p.getInputStream();
					List<String> list=readLine(is);
					for (String s : list) {
						apend(s);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					btn_run.setEnabled(true);
					if (p!=null) {
						p.destroy();
					}
				}
			}
		}).start();
	}
	protected List<String> readLine(InputStream is) throws IOException {
		List<String> list=new ArrayList<>();
		BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
		String s = null;
		while((s= br.readLine())!=null){
			list.add(s);
		}
		return list;
	}

	void apend(String s){
		if (txtMsg.getLineCount()>1000000) {
			txtMsg.setText("");
		}
		txtMsg.append(s+"\n");
		txtMsg.setCaretPosition(txtMsg.getText().length());
	}
}
